/*
 * Class: CustomerView
 * Created by: Mary Joy Pascual
 * Date Created: 06/17/2014
 * Company: Netsuite
*/
package com.netsuite.view;

import java.awt.EventQueue;
import java.awt.Toolkit;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

import java.awt.Dimension;
import java.util.List;

import javax.swing.JPanel;
import javax.swing.JScrollPane;

import com.netsuite.constants.Constants;
import com.netsuite.controller.CustomerController;
import com.netsuite.controller.StatusController;
import com.netsuite.controller.SubsidiaryController;
import com.netsuite.helper.ErrorHelper;
import com.netsuite.helper.MessageViewHelper;
import com.netsuite.logger.LoggerImp;
import com.netsuite.pojo.CustomerPOJO;
import com.netsuite.pojo.StatusPOJO;
import com.netsuite.pojo.SubsidiaryPOJO;
import com.netsuite.webservices.lists.relationships_2014_1.types.CustomerStage;

import javax.swing.JButton;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.border.TitledBorder;

public class CustomerView {

	private static String CLASS_NAME = CustomerView.class.getName();
	
	private CustomerController cusCont;
	private JFrame frmCustomerApplication;
	private JPanel panelViewList;
	private JPanel panelAdd;
	private JScrollPane scrollPane;
	private JTable table;
	private JTextField companyText;
	private JTextField fName;
	private JTextField mName;
	private JTextField lName;
	private JTextField custId;
	private JTextField internalId;
	private JTextField searchField;
	private JComboBox<StatusPOJO> statusCombo;
	private JComboBox <SubsidiaryPOJO> subCombo;
	@SuppressWarnings("rawtypes")
	private JComboBox searchBox;
	private JLabel lblName;
	private JLabel lblCompanyName;
	private JRadioButton companyRadioBtn;
	private JRadioButton indRadioBtn;
	private DefaultTableModel model;
	private JButton btnDelete;
	private JButton goBtnButton;
	


	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					CustomerView window = new CustomerView();
					window.frmCustomerApplication.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public CustomerView() throws ErrorHelper {
		initialize();
	}

	private void initialize() throws ErrorHelper {
		
		LoggerImp.startLog(CLASS_NAME, "initialize()");
		
		Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
		frmCustomerApplication = new JFrame();
		frmCustomerApplication.setLocationRelativeTo(null);
		frmCustomerApplication.setTitle(Constants.APP_NAME);
		frmCustomerApplication.setBounds(100, 100, 759, 846);
		frmCustomerApplication.setLocation(dim.width/2-frmCustomerApplication.getSize().width/2, dim.height/2-frmCustomerApplication.getSize().height/2);
		frmCustomerApplication.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frmCustomerApplication.getContentPane().setLayout(null);
		cusCont = new CustomerController();

		customerListView();
		addCustomerView();
		searchView();
		
		LoggerImp.endLog(CLASS_NAME, "initialize()");
	}
	
	public void customerListView(){
		
		LoggerImp.startLog(CLASS_NAME, "customerListView()");
		
		model = new DefaultTableModel();
		model.addColumn(Constants.INTERNAL_ID);
		model.addColumn(Constants.NAME);
		model.addColumn(Constants.IS_PERSON);
		model.addColumn(Constants.STATUS);
		model.addColumn(Constants.SUBSIDIARY);
		model.addColumn(Constants.F_NAME);
		model.addColumn(Constants.M_NAME);
		model.addColumn(Constants.L_NAME);

		table = new JTable(model);
		table.setAutoCreateRowSorter(true);
		table.setPreferredScrollableViewportSize(new Dimension(400, 500));
		hideColumn(5);
		hideColumn(6);
		hideColumn(7);
		
		table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
			@Override
			public void valueChanged(ListSelectionEvent arg0) {
				if( !arg0.getValueIsAdjusting() && table.getSelectedRow() >= 0) {
					int rowCount = table.getRowCount();
					if(table.getRowCount() != 0){
						int selRow = table.getSelectedRow();
						if(rowCount > selRow){
							btnDelete.setEnabled(true);
							internalId.setText((String)table.getValueAt(selRow, 0));
							boolean isPerson = (boolean)table.getValueAt(selRow, 2);
							if(isPerson){
								fName.setText((String)table.getValueAt(selRow, 5));
								mName.setText((String)table.getValueAt(selRow, 6));
								lName.setText((String)table.getValueAt(selRow, 7));
								indRadioBtn.setSelected(true);
							} else {
								companyText.setText((String)table.getValueAt(selRow, 1));
								companyRadioBtn.setSelected(true);
							}
							
							String status = (String)table.getValueAt(selRow, 3);
							setSelectedStatusValue(statusCombo, status.replace("CUSTOMER-", ""));
							setSelectedSubValue(subCombo,(String)table.getValueAt(selRow, 4));
							custId.setText((String)table.getValueAt(selRow, 1));
						}
					}
				}
			}
		});
		
		panelViewList = new JPanel();
		panelViewList.setBounds(0, 50, 717, 387);
		panelViewList.setLayout(null);
		
		scrollPane = new JScrollPane(table);
		scrollPane.setBounds(12, 13, 705, 361);
		panelViewList.add(scrollPane);
		
		frmCustomerApplication.getContentPane().add(panelViewList);
		
		try {
			generateCustomerList(cusCont.getCustomerList());
		} catch (ErrorHelper e) {
			MessageViewHelper.displayErrorView(e);
		}
		
		LoggerImp.endLog(CLASS_NAME, "customerListView()");
	}
	
	
	public void addCustomerView(){
		
		LoggerImp.startLog(CLASS_NAME, "addCustomerView()");
		
		panelAdd = new JPanel();
		panelAdd.setBounds(12, 13, 717, 775);
		panelAdd.setLayout(null);
		frmCustomerApplication.getContentPane().add(panelAdd);
			
		//PRIMARY INFORMATION
		JPanel panelInfo = new JPanel();
		panelInfo.setBounds(0, 423, 705, 301);
		panelAdd.add(panelInfo);
		panelInfo.setBorder(new TitledBorder(null, Constants.CUS_INFO, TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panelInfo.setLayout(null);
		
		//CUSTOMER ID
		JLabel lblCustomerId = new JLabel(Constants.CUS_ID);
		lblCustomerId.setBounds(97, 43, 105, 16);
		panelInfo.add(lblCustomerId);
		
		custId = new JTextField();
		custId.setBounds(214, 40, 361, 22);
		panelInfo.add(custId);
		custId.setEditable(false);
		custId.setColumns(10);
	
		//COMPANY NAME
		lblCompanyName = new JLabel(Constants.CO_NAME);
		lblCompanyName.setBounds(97, 156, 105, 16);
		panelInfo.add(lblCompanyName);
		
		companyText = new JTextField();
		companyText.setBounds(214, 153, 361, 22);
		companyText.addFocusListener(new FocusListener() {
			@Override
			public void focusLost(FocusEvent arg0) {
				custId.setText(companyText.getText());
			}
			@Override
			public void focusGained(FocusEvent e) {
				custId.setText("");
			}
		});
		panelInfo.add(companyText);
		companyText.setColumns(10);
		
		//INDIVIDUAL NAME
		FocusListener focName = new FocusListener(){
			@Override
			public void focusLost(FocusEvent e) {
				custId.setText(fName.getText()+" "+mName.getText()+" "+lName.getText());
			}
			@Override
			public void focusGained(FocusEvent e) {
				custId.setText("");
			}
			
		};
		
		lblName = new JLabel(Constants.IND_NAME);
		lblName.setBounds(97, 156, 105, 16);
		panelInfo.add(lblName);
		
		fName = new JTextField();
		fName.setBounds(214, 153, 150, 22);
		panelInfo.add(fName);
		fName.setColumns(10);
		fName.addFocusListener(focName);
		
		mName = new JTextField();
		mName.setBounds(365, 153, 42, 22);
		panelInfo.add(mName);
		mName.setColumns(10);
		mName.addFocusListener(focName);
		
		lName = new JTextField();
		lName.setBounds(408, 153, 167, 22);
		panelInfo.add(lName);
		lName.setColumns(10);
		lName.addFocusListener(focName);
		
		lName.setVisible(false);
		mName.setVisible(false);
		fName.setVisible(false);
		lblName.setVisible(false);
	
		//CUSTOMER TYPE
		JLabel lblType = new JLabel(Constants.CUS_TYPE);
		lblType.setBounds(97, 82, 105, 16);
		panelInfo.add(lblType);
		
		ButtonGroup group = new ButtonGroup();
		
		companyRadioBtn = new JRadioButton(Constants.CO);
		companyRadioBtn.setBounds(214, 78, 127, 25);
		panelInfo.add(companyRadioBtn);
		companyRadioBtn.setSelected(true);
		companyRadioBtn.addChangeListener(new ChangeListener() {
			@Override
			public void stateChanged(ChangeEvent e) {
				if(companyRadioBtn.isSelected()){
					companyText.setVisible(true);
					lblCompanyName.setVisible(true);
					fName.setText("");
					mName.setText("");
					lName.setText("");
					custId.setText("");
					fName.setVisible(false);
					mName.setVisible(false);
					lName.setVisible(false);
					lblName.setVisible(false);
				} 
			}
		});
		group.add(companyRadioBtn);
		
		indRadioBtn = new JRadioButton(Constants.IND);
		indRadioBtn.setBounds(214, 108, 127, 25);
		panelInfo.add(indRadioBtn);
		indRadioBtn.addChangeListener(new ChangeListener() {
			@Override
			public void stateChanged(ChangeEvent e) {
				if(indRadioBtn.isSelected()){
					fName.setVisible(true);
					mName.setVisible(true);
					lName.setVisible(true);
					lblName.setVisible(true);
					companyText.setText("");
					companyText.setVisible(false);
					lblCompanyName.setVisible(false);
					custId.setText("");
				}
			}
		});
		group.add(indRadioBtn);
		
		//STATUS LIST
		JLabel lblStatus = new JLabel(Constants.STAT);
		lblStatus.setBounds(97, 203, 56, 16);
		panelInfo.add(lblStatus);
		
		statusCombo = new JComboBox<StatusPOJO>();
		statusCombo.setBounds(214, 200, 361, 22);
		
		StatusController statController = new StatusController();
		try {
			for(StatusPOJO stat : statController.getStatusList()){
				if(stat.getStatusStage().equalsIgnoreCase(CustomerStage.__customer)){
					statusCombo.addItem(new StatusPOJO(stat.getStatusId(), stat.getStatusName()));
				}
			}
		} catch (ErrorHelper e1) {
			MessageViewHelper.displayErrorView(e1);
		}
		
		statusCombo.setSelectedIndex(0);  //Closed Won
		panelInfo.add(statusCombo);
	
		//SUBSIDIARY LIST
		JLabel lblNewLabel = new JLabel(Constants.SUB);
		lblNewLabel.setBounds(100, 250, 102, 16);
		panelInfo.add(lblNewLabel);
		
		subCombo = new JComboBox <SubsidiaryPOJO>();
		subCombo.setBounds(214, 247, 361, 22);
		panelInfo.add(subCombo);
		subCombo.addItem(new SubsidiaryPOJO("", ""));  //Blank
		
		SubsidiaryController subController = new SubsidiaryController();
		try {
			for(SubsidiaryPOJO sub : subController.getSubsidiaryList()){
				subCombo.addItem(new SubsidiaryPOJO(sub.getSubsidiaryId(), sub.getSubsidiaryName()));
			}
		} catch (ErrorHelper e1) {
			MessageViewHelper.displayErrorView(e1);
		}
		
		//BUTTONS
		JButton btnNew = new JButton(Constants.BTN1);
		btnNew.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				resetFields();
			}
		});
		btnNew.setBounds(314, 737, 97, 25);
		panelAdd.add(btnNew);
		
		JButton btnSave = new JButton(Constants.BTN2);
		btnSave.setBounds(608, 737, 97, 25);
		btnSave.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				CustomerPOJO cus = setCustomer();
				String message = validateForm();
				if(message.length() ==0){
					if(internalId.getText().length() == 0){  //ADD
						String id = "";
						try {
							id = cusCont.addCustomer(cus);
							if(id != ""){
								MessageViewHelper.displaySuccessView("Customer Id#"+id+" was successfully generated.");
								model.addRow(new Object[]{id, custId.getText(), indRadioBtn.isSelected(), "CUSTOMER-"+statusCombo.getSelectedItem(), subCombo.getSelectedItem(), fName.getText(), mName.getText(), lName.getText()});
							} else {
								MessageViewHelper.displayErrorView("ERROR in Adding");
							}
						} catch (ErrorHelper e1) {
							MessageViewHelper.displayErrorView(e1);
						}
					} else {                                 //EDIT
						String id = internalId.getText();
						cus.setInternalId(id);
						try {
							cusCont.updateCustomer(cus);
						} catch (ErrorHelper e1) {
							MessageViewHelper.displayErrorView(e1);
						}
						MessageViewHelper.displaySuccessView("Customer Id#"+id+" was successfully updated. \nTo refresh the table, please click the REFRESH Button.");
					}
					resetFields();
				}else {
					MessageViewHelper.displayValidationError(message);
				}
			}
		});
		panelAdd.add(btnSave);
		
		JButton btnRefresh = new JButton(Constants.BTN3);
		btnRefresh.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				resetFields();
				try {
					generateCustomerList(cusCont.getCustomerList());
					MessageViewHelper.displaySuccessView("Customer table is now updated.");
				} catch (ErrorHelper e1) {
					MessageViewHelper.displayErrorView(e1);
				}
			}
		});
		btnRefresh.setBounds(511, 737, 97, 25);
		panelAdd.add(btnRefresh);
		
		btnDelete = new JButton(Constants.BTN4);
		btnDelete.setBounds(412, 737, 97, 25);
		btnDelete.setEnabled(false);
		btnDelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String id = internalId.getText();
				int dialogResult = JOptionPane.showConfirmDialog (null, "Are you sure you want to delete Customer #"+id+"?","Confirm",JOptionPane.YES_NO_OPTION);
				if(dialogResult == JOptionPane.YES_OPTION){
					if(id.length() != 0){
						try {
							cusCont.deleteCustomer(id, null);
							MessageViewHelper.displaySuccessView("Customer #"+id+" was successfully deleted.\nTo refresh the table, please click the REFRESH Button.");
						} catch (ErrorHelper e1) {
							MessageViewHelper.displayErrorView(e1);
						}
						resetFields();
					}
				}
			}
		});
		panelAdd.add(btnDelete);
		
		internalId = new JTextField();
		internalId.setBounds(10, 737, 234, 25);
		internalId.setVisible(false);
		internalId.setColumns(10);
		internalId.setText("");
		panelAdd.add(internalId);
		
		LoggerImp.endLog(CLASS_NAME, "addCustomerView()");
		
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void searchView(){
		
		LoggerImp.startLog(CLASS_NAME, "searchView()");
		
		JLabel lblSearch = new JLabel(Constants.SEARCH);
		lblSearch.setBounds(261, 17, 73, 16);
		panelAdd.add(lblSearch);
		
		String[] searchStrings = { Constants.INTERNAL_ID, Constants.NAME};
		searchBox = new JComboBox(searchStrings);
		searchBox.setBounds(332, 14, 90, 22);
		panelAdd.add(searchBox);
	
		searchField = new JTextField();
		searchField.setBounds(434, 14, 186, 22);
		panelAdd.add(searchField);
		searchField.setColumns(10);
		
		goBtnButton = new JButton(Constants.BTN5);
		goBtnButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String id = (String)searchBox.getSelectedItem();
				String criteria = (String)searchField.getText();
				if(criteria.length() != 0){
					try {
						generateCustomerList(cusCont.searchCustomer(id, criteria));
					} catch (ErrorHelper e) {
						MessageViewHelper.displayErrorView(e);
					}
				}
			}
		});
		
		goBtnButton.setBounds(632, 13, 73, 25);
		panelAdd.add(goBtnButton);
		
		LoggerImp.endLog(CLASS_NAME, "searchView()");
		
	}
	
	public void resetFields(){
		
		LoggerImp.startLog(CLASS_NAME, "resetFields()");
		
		table.clearSelection();
		custId.setText("");
		companyText.setText("");
		fName.setText("");
		lName.setText("");
		mName.setText("");
		internalId.setText("");
		searchField.setText("");
		searchBox.setSelectedIndex(0);
		statusCombo.setSelectedIndex(0);
		subCombo.setSelectedIndex(0);
		lName.setVisible(false);
		mName.setVisible(false);
		fName.setVisible(false);
		lblName.setVisible(false);
		companyText.setVisible(true);
		lblCompanyName.setVisible(true);
		companyRadioBtn.setSelected(true);
		btnDelete.setEnabled(false);
		
		LoggerImp.endLog(CLASS_NAME, "resetFields()");
		
	}
	
	
	public void generateCustomerList(List<CustomerPOJO> custList){
		
		LoggerImp.startLog(CLASS_NAME, "generateCustomerList()");
		
		model.setRowCount(0);
		for (CustomerPOJO cus : custList){
			model.addRow(new Object[]{cus.getInternalId(), cus.getCustomerName(), cus.getIsPerson(), cus.getStatus(), cus.getSubsidiary(), cus.getFirstName(),cus.getMiddleName(),cus.getLastName()});
		}
		
		LoggerImp.endLog(CLASS_NAME, "generateCustomerList()");
	}
	
	public CustomerPOJO setCustomer(){
		
		LoggerImp.startLog(CLASS_NAME, "setCustomer()");
		
		CustomerPOJO customerPojo = new CustomerPOJO();
		customerPojo.setCompanyName(companyText.getText());
		customerPojo.setFirstName(fName.getText());
		customerPojo.setMiddleName(mName.getText());
		customerPojo.setLastName(lName.getText());
		StatusPOJO stat = (StatusPOJO)statusCombo.getSelectedItem();
		customerPojo.setStatus(stat.getStatusId());
		SubsidiaryPOJO sub = (SubsidiaryPOJO) subCombo.getSelectedItem();
		customerPojo.setSubsidiary(sub.getSubsidiaryId());
		
		LoggerImp.endLog(CLASS_NAME, "setCustomer()");
		
		return customerPojo;
	}
	
	private void hideColumn(int index) {
		
	   LoggerImp.startLog(CLASS_NAME, "hideColumn()");
	   
	   table.getColumnModel().getColumn(index).setMinWidth(0);
	   table.getColumnModel().getColumn(index).setMaxWidth(0);
	   table.getColumnModel().getColumn(index).setWidth(0);
	   table.getColumnModel().getColumn(index).setPreferredWidth(0);
	   
	   LoggerImp.endLog(CLASS_NAME, "hideColumn()");
	   
	}
	
	public void setSelectedStatusValue(JComboBox<StatusPOJO>comboBox, String value){
		
		LoggerImp.startLog(CLASS_NAME, "setSelectedStatusValue()");
		
		StatusPOJO item = null;
		for (int i = 0; i < comboBox.getItemCount(); i++){
            item = comboBox.getItemAt(i);
            if (item.getStatusName().equalsIgnoreCase(value)){
                comboBox.setSelectedIndex(i);
                break;
            }
        }
		
		LoggerImp.endLog(CLASS_NAME, "setSelectedStatusValue()");
    }
	
	public void setSelectedSubValue(JComboBox<SubsidiaryPOJO>comboBox, String value){
		
		LoggerImp.startLog(CLASS_NAME, "setSelectedSubValue()");
		
		SubsidiaryPOJO item = null;
		for (int i = 0; i < comboBox.getItemCount(); i++){
            item = comboBox.getItemAt(i);
            if (item.getSubsidiaryName().equalsIgnoreCase(value)){
                comboBox.setSelectedIndex(i);
                break;
            }
        }
		
		LoggerImp.endLog(CLASS_NAME, "setSelectedSubValue()");
    }
	
	public String validateForm(){
		
		LoggerImp.startLog(CLASS_NAME, "validateForm()");
		
		String message = "";
		if(custId.getText().length() == 0){
			message += Constants.CUS_VAL;
		} 
		if(indRadioBtn.isSelected()){
			if(	fName.getText().length() == 0){
				message += Constants.FN_VAL;
			}
			if(	lName.getText().length() == 0){
				message += Constants.LN_VAL;
			}
		} 
		if(companyRadioBtn.isSelected()){
			if(	companyText.getText().length() == 0){
				message += Constants.CO_VAL;
			}
		}
		if(subCombo.getSelectedIndex() == 0){
			message += Constants.SUB_VAL;
		}
		
		LoggerImp.endLog(CLASS_NAME, "validateForm()");
		
		return message;
		
	}
	

}




